<template>
  <div class="sort">
    <h2>商品分类管理</h2>
    <div class="search-container">
      <el-input class="el-input" v-model="searchQuery" placeholder="搜索分类名称" @keyup.enter="searchsort"></el-input>
      <select class="el-input border" v-model="selectedCategory">
        <option value="">商品分类</option>
        <option v-for="(category, index) in uniqueGoodsSorts" :key="index" :value="category">{{ category }}</option>
      </select>
      <el-button class="el-button search" @click="searchsort">
        <img src="../../assets/icons/none.png" alt="">
        刷新</el-button>
      <el-button class="el-button add" @click="openAddDialog">
        <img src="../../assets/img/add.png" alt="">
        新增分类</el-button>
      <el-table :data="currentsort" stripe ref="userTable" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="SortId" label="分类ID"></el-table-column>
        <el-table-column prop="GoodsSort" label="商品总分类"></el-table-column>
        <el-table-column label="分类名称" width="200">
          <template slot-scope="scope">
            <img :src="scope.row.SortUrl" alt="" style="width: 30px; height: 30px;">
            <span style="position: relative;top: -8px; left: 15px;">{{ scope.row.SortName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="SortNumber" label="排序值" width="130"></el-table-column>
        <el-table-column prop="SortTime" label="注册时间" width="250">
          <template slot-scope="scope">
            {{ formatTime(scope.row.SortTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="SortState" label="状态">
          <template slot-scope="scope">
            <span :style="{
              backgroundColor: getSortStateColor(scope.row.SortState),
              color: getSortStateTextColor(scope.row.SortState),
              padding: '3px 5px', borderRadius: '3px'
            }">
              {{ scope.row.SortState }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <img src="../../assets/img/write.png" style="width: 20px; height: 25px; margin-right: 15px;" type="primary"
              @click="openEditDialog(scope.row)">
            <img src="../../assets/img/remove.png" style="width: 30px; height: 25px;" type="danger"
              @click="openDeleteDialog(scope.row)">
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
        :page-sizes="[10, 20, 30]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
        :total="totalsort">
      </el-pagination>
    </div>

    <!-- 删除确认弹窗 -->
    <el-dialog :visible.sync="deleteDialogVisible" title="删除分类">
      <p>确定要删除{{ currentDeleteSort.SortName }} 分类吗？此操作不可恢复。</p>
      <span style="margin-top: 30px;display: block;">
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="sortdel">删除</el-button>
      </span>
    </el-dialog>

    <!-- 分类信息弹窗 -->
    <el-dialog :visible.sync="addDialogVisible" title="新增分类" width="700px">
      <el-form :model="newSort" ref="addForm" label-width="150px" style="display: flex;justify-content: space-between;">
        <div class="left">
          <el-form-item label="总分类名称" prop="GoodsSort">
            <el-select v-model="newSort.GoodsSort" placeholder="请选择总分类">
              <el-option v-for="category in uniqueGoodsSorts" :key="category" :label="category"
                :value="category"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="分类ID" prop="SortId">
            <el-input v-model="newSort.SortId" disabled></el-input>
          </el-form-item>
          <el-form-item label="分类名称" prop="SortName">
            <el-input v-model="newSort.SortName"></el-input>
          </el-form-item>
          <el-form-item label="排序值" prop="SortNumber">
            <el-input v-model="newSort.SortNumber" disabled></el-input>
          </el-form-item>
          <el-form-item label="状态" prop="SortState">
            <el-select v-model="newSort.SortState" placeholder="请选择状态">
              <el-option label="开启" value="开启"></el-option>
              <el-option label="禁用" value="禁用"></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div class="right" style="margin-left: 50px;">
          <img :src="newSort.SortUrl  || 'http://127.0.0.1:3000/picture/1.png'"  style="border: 1px solid #ccc; width: 200px;height: 200px;" alt="">
          <form class="uploadForm" enctype="multipart/form-data">
            <input type="file" name="image" placeholder=" 图片" class="img" ref="newImageInput">
            <button type="button" class="btn" @click="sendImage('add')">完成</button>
          </form>
        </div>
      </el-form>
      <span style="margin: 30px 40px 0 90px;display: block;">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="sortpost"></el-button>
      </span>
    </el-dialog>

    <!-- 修改分类信息弹窗 -->
    <el-dialog :visible.sync="editDialogVisible" title="修改分类" width="700px">
      <el-form :model="currentEditSort" ref="editForm" label-width="150px"
        style="display: flex;justify-content: space-between;">
        <div class="left">
          <el-form-item label="总分类名称" prop="GoodsSort">
            <el-input v-model="currentEditSort.GoodsSort"></el-input>
          </el-form-item>
          <el-form-item label="分类名称" prop="SortName">
            <el-input v-model="currentEditSort.SortName"></el-input>
          </el-form-item>
          <el-form-item label="分类ID" prop="SortId">
            <el-input v-model="currentEditSort.SortId"></el-input>
          </el-form-item>
          <el-form-item label="排序值" prop="SortNumber">
            <el-input v-model="currentEditSort.SortNumber"></el-input>
          </el-form-item>
          <el-form-item label="状态" prop="SortState">
            <el-select v-model="currentEditSort.SortState" placeholder="请选择状态">
              <el-option label="开启" value="开启"></el-option>
              <el-option label="禁用" value="禁用"></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div class="right" style="margin-left: 50px;">
          <img :src="currentEditSort.SortUrl  || 'http://127.0.0.1:3000/picture/1.png'"  style="border: 1px solid #ccc; width: 200px;height: 200px;" alt="">
          <form class="uploadForm" enctype="multipart/form-data">
            <input type="file" name="image" placeholder=" 更换图片" class="img" ref="editImageInput">
            <button type="button" class="btn" @click="sendImage('edit')">完成</button>
          </form>
        </div>
      </el-form>
      <span style="margin: 30px 40px 0 90px;display: block;">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="sortfix">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Message } from 'element-ui';
import jq from "jquery";
import AjaxObj from "../../utils/jqAjaxUrl";
export default {
  data() {
    return {
      sort: [],
      // 搜索关键词
      searchQuery: '',
      // 当前页码
      currentPage: 1,
      // 每页显示数量
      pageSize: 10,
      // 总分类名称数
      totalsort: 0,
      // 选中的分类名称列表
      selectedsort: [],
      // 删除确认弹窗是否显示
      deleteDialogVisible: false,
      // 当前要删除的分类名称
      currentDeleteSort: {},
      // 分类信息弹窗是否显示
      addDialogVisible: false,
      // 分类信息
      newSort: {
        SortId: null,
        SortUrl: 'http://127.0.0.1:3000/picture/1.png',
        SortName: '',
        SortNumber: '',
        GoodsSort: '',
        SortTime: new Date().toLocaleString(),
        SortState: '开启',
        id: null,
      },
      // 编辑分类信息弹窗是否显示
      editDialogVisible: false,
      // 当前要编辑的分类
      currentEditSort: {},
      uniqueGoodsSorts: [],
      selectedCategory: ''
    };
  },
  computed: {
    // 计算当前页的分类名称
    currentsort() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      const filteredsort = this.sort
        .filter(sort =>
          (this.selectedCategory === '' || sort.GoodsSort === this.selectedCategory) &&
          sort.SortName.includes(this.searchQuery)
        )
        .sort((a, b) => {
          if (a.SortId !== b.SortId) {
            return a.SortId - b.SortId;
          } else {
            const aNum = a.SortNumber ? parseInt(a.SortNumber, 10) : -Infinity;
            const bNum = b.SortNumber ? parseInt(b.SortNumber, 10) : -Infinity;
            return aNum - bNum;
          }
        });
      return filteredsort.slice(start, end);
    }
  },
  watch: {
    'newSort.GoodsSort'(newVal) {
      if (newVal) {
        this.generateSortIdAndNumber();
      }
    }
  },
  mounted() {
    this.goodssort();

  },
  methods: {
    sendImage(type) { // ：通过参数区分场景
      const _this = this;
      let inputRef;
      // 根据场景获取对应的输入框
      if (type === 'add') {
        inputRef = this.$refs.newImageInput;
      } else if (type === 'edit') {
        inputRef = this.$refs.editImageInput;
      }
      if (!inputRef || !inputRef.files[0]) {
        Message.error('请选择图片文件');
        return;
      }
      const formData = new FormData();
      formData.append('image', inputRef.files[0]);
      // 传递对应的id（时用newSort.id，编辑时用currentEditSort.id）
      formData.append('id', type === 'add' ? _this.newSort.id : _this.currentEditSort.id);

      jq.ajax({
        type: "post",
        url: AjaxObj.url + "/GoodsSortPicture", // 需确认后端接口是否正确
        data: formData,
        processData: false,
        contentType: false,
        success(res) {
          if (res.status === 200 && res.data && res.data.SortUrl) {
            // 根据场景更新对应的数据源
            type === 'add' ? _this.newSort.SortUrl = res.data.SortUrl : _this.currentEditSort.SortUrl = res.data.SortUrl;
          } else {
            Message.error('图片上传失败');
          }
        },
        error(err) {
          console.error('上传错误:', err);
          Message.error('网络错误，请重试');
        }
      });
    },
    //商品分类渲染
    goodssort() {
      let _this = this
      jq.ajax({
        type: "get",
        url: "http://127.0.0.1:3000/goodssort",
        success(res) {
          console.log('res', res)
          if (res.data == "") {
            return
          } else {
            _this.sort = res.data
            // 生成唯一商品分类列表
            _this.uniqueGoodsSorts = [...new Set(res.data.map(item => item.GoodsSort))];
            console.log('_this.sort', _this.sort)
          }
        }
      })
    },
    // 修改删除方法
    sortdel() {
      let _this = this;
      jq.ajax({
        type: 'delete',
        url: `http://127.0.0.1:3000/sortdel/${this.currentDeleteSort.id}`, // 传递 id 到后端
        success(res) {
          if (res.status === 200) {
            _this.deleteDialogVisible = false;
            Message.success(`删除分类 ${_this.deleteDialogVisible.SortName} 成功`);
          } else {
            Message.error('删除失败');
          }
        },
        error(err) {
          console.error('删除失败:', err);
          Message.error('删除失败');
        }
      });
    },
    // 修改方法
    sortpost() {
      console.log('进入 sortpost 方法')
      let _this = this;
      jq.ajax({
        type: 'post',
        url: 'http://127.0.0.1:3000/sortpost',
        data: {
          SortNumber: _this.newSort.SortNumber,
          SortUrl: _this.newSort.SortUrl,
          SortName: _this.newSort.SortName,
          SortId: _this.newSort.SortId,
          SortTime: _this.newSort.SortTime,
          SortState: _this.newSort.SortState,
          GoodsSort: _this.newSort.GoodsSort,
          id: _this.newSort.id,
        },
        success(res) {
          console.log('接口原始响应:', res); // 先打印完整响应，确认数据结构 
          if (typeof res === 'object' && res !== null) {
            if (res.status === 200) {
              _this.addDialogVisible = false;
              Message.success(`添加分类 ${_this.newSort.SortName} 成功`);
              console.log('成功:', res.data);
              _this.goodssort(); // 成功后重新获取数据
            } else {
              console.error('分类失败，服务器返回非成功状态:', res);
            }
          }
        },
        error(err) {
          console.error('分类失败，请求发生错误:', err);
          Message.error('分类失败，请求发生错误');
        }
      });
    },
    // 修改编辑方法
    sortfix() {
      let _this = this;
      jq.ajax({
        type: 'put',
        url: `http://127.0.0.1:3000/sortfix`,
        data: this.currentEditSort,
        success(res) {
          if (res.status === 200) {
            _this.editDialogVisible = false;
            Message.success(`修改分类 ${_this.currentEditSort.SortName} 成功`);
            _this.goodssort();
          } else {
            Message.error('修改失败');
          }
        },
        error(err) {
          console.error('修改失败:', err);
          Message.error('修改失败');
        }
      });
    },
    generateSortIdAndNumber() {
      const selectedCategory = this.newSort.GoodsSort;

      // 生成分类ID（按分类分组自增）
      const categoryItems = this.sort.filter(item => item.GoodsSort === selectedCategory);
      const maxSortId = categoryItems.length > 0
        ? Math.max(...categoryItems.map(item => item.SortId))
        : 0;
      this.newSort.SortId = maxSortId + 1;
      const validNumbers = categoryItems
        .map(item => item.SortNumber)
        .filter(num => !isNaN(num) && num !== null && num !== '');

      const maxSortNumber = validNumbers.length > 0
        ? Math.max(...validNumbers.map(num => parseInt(num, 10)))
        : 0;
      this.newSort.SortNumber = (maxSortNumber + 1).toString();
    },

    formatTime(timeStr) {
      if (!timeStr) return '';
      const date = new Date(timeStr);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    },
    // 搜索分类名称
    searchsort() {
      this.currentPage = 1;
      const filteredsort = this.sort.filter(user =>
        user.SortName.includes(this.searchQuery)
      );
      console.log('过滤后的分类数据：', filteredsort); // 打印过滤后的分类名称数据
      this.totalsort = filteredsort.length;
    },
    // 每页数量改变时触发
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      const filteredsort = this.sort.filter(user =>
        user.SortName.includes(this.searchQuery)
      );
      this.totalsort = filteredsort.length;
    },
    // 当前页码改变时触发
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      const filteredsort = this.sort.filter(user =>
        user.SortName.includes(this.searchQuery)
      );
      this.totalsort = filteredsort.length;
    },
    // 打开删除确认弹窗
    openDeleteDialog(user) {
      this.currentDeleteSort = user;
      this.deleteDialogVisible = true;
    },

    // 打开编辑用户信息弹窗
    openEditDialog(user) {
      this.currentEditSort = { ...user };
      this.editDialogVisible = true;
    },
    // 打开分类名称信息弹窗
    openAddDialog() {
      this.newSort = {
        SortId: '',
        SortUrl: 'http://127.0.0.1:3000/picture/1.png ',
        SortName: '',
        SortNumber: '',
        id: this.generateNewId(),
        GoodsSort: '',
        SortTime: new Date().toLocaleString(),
        SortState: '开启'
      };
      this.addDialogVisible = true;
    },

    // 生成新的分类ID
    generateNewId() {
      const maxId = Math.max(...this.sort.map(user => user.id));
      return maxId + 1;
    },
    // 状态返回对应的颜色
    getSortStateColor(SortState) {
      switch (SortState) {
        case '开启':
          return '#E8F5E9';
        case '禁用':
          return '#FFE4E1';
        default:
          return 'transparent';
      }
    },
    getSortStateTextColor(SortState) {
      switch (SortState) {
        case '开启':
          return '#006400';
        case '禁用':
          return '#8B0000';
        default:
          return 'black';
      }
    },
    // 处理表格选中项变化
    handleSelectionChange(selectedsort) {
      this.selectedsort = selectedsort;
    }
  },
  created() {
    this.totalsort = this.sort.length;
  }
};
</script>

<style lang="less" scoped>
.sort {
  padding: 70px 20px 20px 230px;
  background-color: #F9FAFB;
  width: 100%;

  h2 {
    display: block;
    visibility: visible;
    margin-left: 10px;
  }

  .search-container {
    box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3);
    background-color: white;
    position: relative;
    margin: 20px 10px;
    border-radius: 10px;
    border: 1px solid #e9e8e8;
    width: 99%;

    .el-input {
      margin: 20px;
      width: 300px;
    }

    .border {
      border: 1px solid #e2e2e2;
      border-radius: 5px;
      background-color: transparent;
      padding: 10px 15px;
      margin-right: 35px;
      color: #747474;
    }

    .el-button {
      padding: 10px 15px;
      border-radius: 6px;

      img {
        position: relative;
        top: 2px;
        width: 15px;
        height: 15px;
      }
    }

    .add {
      background-color: #007bff;
      color: white;
      position: absolute;
      top: 18px;
      right: 20px;
    }
  }
}
</style>